﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;
using Mindfor.Web.Config;
using Mindfor.Web.Data;
using NHibernate;
using NHibernate.Linq;

namespace Mindfor.Web.Modules.Users
{
	/// <summary>
	/// Contains controllers to manage current user and users list.
	/// </summary>
	public class UsersModule : ModuleBase
	{
		public UsersModule()
		{
			IsAlwaysEnabled = true;
		}

		/// <summary>
		/// Mail template name for registration.
		/// </summary>
		public const string MailTemplateRegister = "Register";

		/// <summary>
		/// Mail template name for registration with email approve.
		/// </summary>
		public const string MailTemplateRegisterApprove = "RegisterApprove";

		/// <summary>
		/// Mail template name for recover password.
		/// </summary>
		public const string MailTemplateRecoverPwd = "RecoverPwd";

		/// <summary>
		/// Returns modules names current one dependent on.
		/// </summary>
		public override string[] GetDependencyModules()
		{
			return new string[] { CmsConstants.SystemModuleName, "Mail" };
		}

		/// <summary>
		/// Registers module. For example, custom routes.
		/// </summary>
		/// <param name="info">Registration data.</param>
		public override void Register(ModuleRegistrationData info)
		{
			base.Register(info);

			// create mail templates
			using (ITransaction t = info.Data.BeginTransaction())
			{
				MailTemplateType registerTemplateType = info.Data.Query<MailTemplateType>().Get(MailTemplateRegister, Name);
				if (registerTemplateType == null)
				{
					registerTemplateType = new MailTemplateType(MailTemplateRegister, Name);
					registerTemplateType.Description = "{login} - login\n{pwd} - password\n{url} - activation url\n{site} - site url";
					info.Data.Save(registerTemplateType);
				}

				MailTemplateType registerApproveTemplateType = info.Data.Query<MailTemplateType>().Get(MailTemplateRegisterApprove, Name);
				if (registerApproveTemplateType == null)
				{
					registerApproveTemplateType = new MailTemplateType(MailTemplateRegisterApprove, Name);
					registerApproveTemplateType.Description = "{login} - login\n{pwd} - password\n{url} - activation url\n{site} - site url";
					info.Data.Save(registerApproveTemplateType);
				}

				MailTemplateType recoverPwdTemplateType = info.Data.Query<MailTemplateType>().Get(MailTemplateRecoverPwd, Name);
				if (recoverPwdTemplateType == null)
				{
					recoverPwdTemplateType = new MailTemplateType(MailTemplateRecoverPwd, Name);
					recoverPwdTemplateType.Description = "{login} - login\n{url} - recover url\n{site} - site url";
					info.Data.Save(recoverPwdTemplateType);
				}

				t.Commit();
			}
		}
	}
}
